#include "dmdlg.h"
#include "ui_dmdlg.h"
#include "common.h"
#include "tabledefine.h"
#include "managementdatabaseoperations.h"
#include "productdatabaseoperations.h"
#include "errorcode.h"
#include <QMenu>
#include <QFileDialog>

extern QSqlDatabase ManagementDB;
extern QSqlDatabase productDB;

DMDlg::DMDlg(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DMDlg)
{
    ui->setupUi(this);
    
    error = new ErrorToDo;
    
    //Connect and init ManagementDB
    if(!connectManagementDB(MANAGEMENTDB_NAME))
    {
        exit(CONNECT_MANAGEMENTDB_FAILED);
    }
    if(!initManagementDB())
    {
        exit(INIT_MANAGEMENTDB_FAILED);
    }
    
    //Create database model
    model = new QSqlQueryModel;
    model->setQuery(QString("select * from %1").arg(DM_TABLE_NAME), ManagementDB);
    model->setHeaderData(1, Qt::Horizontal, "名称");
    model->setHeaderData(2, Qt::Horizontal, "厂家");
    model->setHeaderData(3, Qt::Horizontal, "订货号");
    model->setHeaderData(4, Qt::Horizontal, "媒质类型");
    model->setHeaderData(5, Qt::Horizontal, "应用");
    model->setHeaderData(6, Qt::Horizontal, "版本");
    model->setHeaderData(7, Qt::Horizontal, "数据库文件名");
    
    //Set database model and tableview
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);  //设置选中时选中一行
    ui->tableView->setModel(model);
    ui->tableView->hideColumn(0);  //隐藏id列(第0列)
    ui->tableView->resizeColumnsToContents();
    ui->tableView->verticalHeader()->hide();
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//均分列
    
    //Create delete device and add device action
    actionDelProduct = new QAction("删除", this);
    actionAddDeviceToRoom = new QAction("添加设备", this);
    
    //Connect import、delete、open device's signals and slots  
    connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), 
            this, SLOT(setTableViewMenu()));  //记得将ui界面中设置为customContextMenu
    connect(ui->importDeviceBtn, SIGNAL(clicked(bool)),
            this, SLOT(importProductFile()));
    connect(actionDelProduct, SIGNAL(triggered(bool)),
            this, SLOT(delProduct()));
    connect(actionAddDeviceToRoom, SIGNAL(triggered(bool)),
            this, SLOT(addDeviceToRoom()));
    connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)),
            this, SLOT(addDeviceToRoom()));
    connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)),
            this, SLOT(accept()));
}

DMDlg::~DMDlg()
{
    delete error;
    ManagementDB.close();
    delete ui;
}

void DMDlg::updateTableView()
{
    model->setQuery(QString("select * from %1").arg(DM_TABLE_NAME), ManagementDB);
    ui->tableView->resizeColumnsToContents();
}

void DMDlg::setTableViewMenu()
{
    int column = ui->tableView->currentIndex().column();
    if(column < 0)
        return ;
    
    QMenu *popMenu = new QMenu(this);
    
    popMenu->addAction(actionAddDeviceToRoom);
    popMenu->addAction(actionDelProduct);
    
    popMenu->exec(QCursor::pos());
}

void DMDlg::importProductFile()
{
    QFileDialog *fileDialog = new QFileDialog(this);
    fileDialog->setWindowTitle(tr("导入产品数据库文件"));
    fileDialog->setDirectory(".");
    //设置文件过滤器
    fileDialog->setNameFilter(QString("设备数据库文件(*%1)").arg(SUFFIX));
    fileDialog->setViewMode(QFileDialog::Detail);
    
    //打印所选择的文件名
    QStringList filePathNames;
    QString fileName;
    if(fileDialog->exec())
    {
        QFileInfo fi;
        filePathNames = fileDialog->selectedFiles();
        fi = QFileInfo(filePathNames.at(0));
        fileName = fi.fileName();
        qDebug()<<"file:"<<__FILE__<<"line:"<<__LINE__<<fileName;
    }
    else
    {
        return;
    }
    
    //目前的做法是将导入的设备数据库文件复制
    QString destFile = QString(DB_PATH).append(fileName);
    copyFileToPath(filePathNames.at(0), destFile, 0);
    qDebug()<<"file:"<<__FILE__<<"line:"<<__LINE__<<destFile;
    QString fileNameNoSuffix = fileName.left(fileName.length() - 3);
    qDebug()<<"file:"<<__FILE__<<"line:"<<__LINE__<<fileNameNoSuffix;
    
    //连接产品数据库
    if(!connectProductDB(destFile))
    {
        qCritical()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"连接产品数据库失败";
        error->showCriticalMsg(this, "连接产品数据库失败");
        return;
    }
    
    //在设备管理表通过设备名判断设备是否已存在
    int res = isProductNameExistsInDM(fileNameNoSuffix);
    if(res< 0)
    {
        qCritical()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"数据库操作错误，查询DM设备名失败";
        error->showCriticalMsg(this, "数据库操作错误，查询DM设备名失败");
        return;
    }
    if(!res)
    {
        qWarning()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"产品已存在，请勿重复导入";
        error->showWarningMsg(this, "产品已存在，请勿重复导入");
        return;
    }
    
    //附加产品数据库到管理数据库
    QSqlQuery query(ManagementDB);
    if(!query.exec(QString("ATTACH DATABASE  '%1' as productAndManagement").arg(destFile)))
    {
        qCritical()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"attach 失败："<<query.lastError();
        error->showCriticalMsg(this, "attach失败");
        return;
    }
    qDebug()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"attach success";
    
    //将产品信息插入到设备管理表
    QString tableName = QString("productAndManagement.").append(PRODUCT_INFO_TABLE_NAME);
    if(!query.exec(QString("insert into %1 (%2,%3,%4,%5,%6,%7,%8) select * from %11")
                   .arg(DM_TABLE_NAME)
                   .arg(NAME)
                   .arg(MANUFACTURERS)
                   .arg(ORDER_NUM)
                   .arg(MEDIUM_TYPE)
                   .arg(APP_PROGRAM)
                   .arg(VERSION)
                   .arg(DEVICEDB_NAME)
                   .arg(tableName)))
    {
        qCritical()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"插入产品信息到产品管理表失败";
        error->showCriticalMsg(this, "插入产品信息到产品管理表失败");
        return;
    }
    //从管理数据库中分离产品数据库并关闭连接的数据库（如果不关闭连接，数据库文件无法删除）
    query.exec("DETACH DATABASE 'productAndManagement'");
    productDB.close();
    
    updateTableView();  //更新产品管理表显示
}

void DMDlg::delProduct()
{
    //获取要删除的设备信息
    int row = ui->tableView->currentIndex().row();  //获取当前行
    QModelIndex index = model->index(row, 0);  //获取当前行的第零列(第0列存产品id，隐藏列)
    QVariant data = model->data(index);
    int productID = data.toInt();
    QString deviceFileName= QString(DB_PATH).append(model->data(model->index(row, 7)).toString()).append(SUFFIX);  //设备数据库文件名
    qDebug()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"deviceFileName,productID:"<<deviceFileName<<productID;
    
    //删除设备数据库文件
    QFile file(deviceFileName);
    if(file.exists())
    {
        QDir dir;
        qDebug()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"找到要删除的文件，此时位置："<<dir.currentPath();
        if(!file.remove())
        {
            qCritical()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"删除产品数据库文件失败";
            error->showCriticalMsg(this, "删除产品数据库文件失败");
            return;
        }
        qDebug()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"删除文件成功";
    }
    else
    {
        qCritical()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"要删除的产品数据库文件不存在";
        error->showCriticalMsg(this, "要删除的产品数据库文件不存在");
        return;
    }
    
    //根据id删除设备管理表中的数据
    if(!deleteProduct(productID))
    {
        qCritical()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"在产品管理表中删除产品信息失败";
        error->showCriticalMsg(this, "在产品管理表中删除产品信息失败");
        return ;
    }
    
    updateTableView();
}

void DMDlg::addDeviceToRoom()
{
    int row = ui->tableView->currentIndex().row();  //获取当前行
    
    this->selectProductID = (model->data(model->index(row, 0))).toInt();  //获取id，当前第0列
    this->selectProductName = (model->data(model->index(row, 1))).toString();  //产品名称，第1列
    this->selectProductManufacture = (model->data(model->index(row, 2))).toString();  //获取厂家信息
    this->selectProductOrderNum = (model->data(model->index(row, 3))).toString();  //获取订货号
    this->selectProductMediumType = (model->data(model->index(row, 4))).toString();  //获取媒质类型
    this->selectProductAppProgram = (model->data(model->index(row, 5))).toString();  //获取应用程序名
    this->selectProductVersion = (model->data(model->index(row, 6))).toString();  //获取版本号
    this->selectProductDBName = (model->data(model->index(row, 7))).toString();  //产品数据库名，暂时和产品名相同
    qDebug()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"选取的要添加的设备型号为："<<selectProductName;
    
    this->accept();
}

bool DMDlg::copyFileToPath(QString sourceDir ,QString toDir, bool coverFileIfExist)
{
	toDir.replace("\\","/");
	if(sourceDir == toDir){
		return true;
	}
	if(!QFile::exists(sourceDir)){
		return false;
	}
	QDir *createfile     = new QDir;
	bool exist = createfile->exists(toDir);
	if (exist){
		if(coverFileIfExist){
			createfile->remove(toDir);
		}
	}
 
	if(!QFile::copy(sourceDir, toDir))
	{
		return false;
	}
	return true;
}
